package com.bsoft.aidltest;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.bsoft.aidlservertest.Calculate;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText edt_arg1, edt_arg2;
    private TextView tv_solution;
    private Button btn_submit;

    private Calculate mService;

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = Calculate.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        edt_arg1 = (EditText) findViewById(R.id.edt_arg1);
        edt_arg2 = (EditText) findViewById(R.id.edt_arg2);
        btn_submit = (Button) findViewById(R.id.btn_submit);
        tv_solution = (TextView) findViewById(R.id.tv_solution);

        btn_submit.setOnClickListener(this);

        Intent intent = new Intent();
        intent.setAction("com.bsoft.aidlservertest.CalculateUtils");
        intent.setPackage("com.bsoft.aidlservertest");
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_submit:
                float arg1 = Float.parseFloat(edt_arg1.getText().toString());
                float arg2 = Float.parseFloat(edt_arg2.getText().toString());
                float solution;
                try {
                    solution = mService.multiplication(arg1, arg2);
                    tv_solution.setText(solution + "");
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mConnection != null) {
            unbindService(mConnection);
        }
    }
}
